package ita.class1.group2.supermarket.customer.realm;

import ita.class1.group2.supermarket.common.annotation.Autowired;
import ita.class1.group2.supermarket.common.annotation.Component;
import ita.class1.group2.supermarket.common.auth.*;
import ita.class1.group2.supermarket.common.auth.exception.CredentialsException;
import ita.class1.group2.supermarket.common.auth.exception.DisabledAccountException;
import ita.class1.group2.supermarket.common.auth.exception.UnknownAccountException;
import ita.class1.group2.supermarket.customer.pojo.User;
import ita.class1.group2.supermarket.customer.service.UserService;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Component
public class JDBCRealm implements AuthorizingRealm {

    @Autowired private UserService userService;

    @Override
    public boolean isPermitted(Permission permission) {
        return false;
    }

    @Override
    public boolean isPermittedAll(Set<Permission> permissions) {
        return false;
    }

    @Override
    public String getName() {
        return "C_USER_REALM";
    }

    @Override
    public boolean support(AuthenticationToken token) {
        return token instanceof UsernamePasswordToken;
    }

    @Override
    public AuthorizingInfo getAuthorizingInfo(AuthenticationToken token) {
        Map<String, String> conditions = new HashMap<String, String>();
        conditions.put("username", ((UsernamePasswordToken) token).getPrincipal());
        List<User> users = userService.findByCondition(conditions);
        if (users.size() == 0) {
            throw new UnknownAccountException();
        } else if (!users.get(0).getPassword().equals(((UsernamePasswordToken) token).getCredentials())) {
            throw new CredentialsException();
        } else if (users.get(0).getStatus().equals(User.FORBIDDEN)) {
            throw new DisabledAccountException();
        }
        return users.get(0);
    }

}
